/*
 * Copyright (c) 2013. mCruncher Sdn Bhd, Cyberjaya, Malaysia.
 * All rights reserved.
 */

package com.mcruncher.properties.converter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @author Arunachalam
 * @since 1.0
 */
public class FileConverterUtils
{
    public static final String XML_EXTENSION = ".xml";
    public static final String PROPERTY_EXTENSION = ".properties";

    public static void convertToXmlFile(File propertyFile, String locale)
    {
        try {
            //Load from property file
            FileInputStream inputStream = new FileInputStream(propertyFile);
            Properties properties = new Properties();
            properties.load(inputStream);

            //Store xml file
            String xmlFileName = getFileName(propertyFile.getName(), locale, XML_EXTENSION);
            OutputStream outputStream = new FileOutputStream(new File(propertyFile.getParent(), xmlFileName));
            properties.storeToXML(outputStream, null, "UTF-8");

            inputStream.close();
            outputStream.close();
        } catch (Exception ex) {
            System.out.println("Error occurred while converting xml file " + ex);
        }
    }

    public static void convertToPropertyFile(File xmlFile, String locale)
    {
        try {
            //Load from xml file
            FileInputStream inputStream = new FileInputStream(xmlFile);
            Properties properties = new Properties();
            properties.loadFromXML(inputStream);

            //Store property file
            String propertyFileName = getFileName(xmlFile.getName(), locale, PROPERTY_EXTENSION);
            OutputStream outputStream = new FileOutputStream(new File(xmlFile.getParent(), propertyFileName));
            properties.store(outputStream, null);

            inputStream.close();
            outputStream.close();
        } catch (Exception ex) {
            System.out.println("Error occurred while converting property file " + ex);
        }
    }

    static String getFileName(String fileName, String locale, String fileExtension)
    {
        StringBuilder builder = new StringBuilder();
        builder.append(getFilenameWithoutExtension(fileName));
        builder.append(locale);
        builder.append(fileExtension);
        return builder.toString();
    }

    static String getFilenameWithoutExtension(String fileName)
    {
        return fileName.substring(0, fileName.indexOf('.'));
    }

    static String getFileNameExtension(String fileName)
    {
        return fileName.substring(fileName.indexOf('.'));
    }
}
